download_dir=/opt
jar_filename=nginxWebUI.jar
jar_path=$download_dir/$jar_filename
JAVA_OPTIONS="-Xmx64m"
server_port=8080
project_home=/home/nginxWebUI/
mysql_host=localhost
mysql_port=3306
spring_database_type=mysql
spring_datasource_dbname="nginxwebui"
spring_datasource_username=$spring_datasource_dbname
spring_datasource_password=$spring_datasource_dbname
spring_datasource_url=jdbc:mysql://$mysql_host:$mysql_port/$spring_datasource_dbname
check_url="www.baidu.com"
startup_cmd="java $JAVA_OPTIONS -jar $jar_path --project.home=$project_home --server.port=$server_port --knife4j.production=false"
function echoGreen() {
	echo -e "\033[34m[INFO] $1\033[0m"
}
function echoYellow() {
	echo -e "\033[33m[WARN] $1\033[0m"
}
function echoRed() {
	echo -e "\033[31m[ERROR] $1\033[0m"
}
function app_start() {
	ping -c 4 $check_url &>/dev/null
	if [[ 0 != $? ]]; then
		echoRed "未连接到互联网"
		exit 1
	fi
	[[ ! -e $jar_path ]] && curl -#o $jar_path $(curl -s https://www.nginxwebui.cn | egrep -o "https?://file.*\.jar")
	check_datasource=$(curl -sS -vv -m 3 telnet://$mysql_host:$mysql_port 2>&1 | grep "Connected" | wc -l)
	if [[ "mysql" == "$spring_database_type" ]]; then
		if [[ 0 != $check_datasource ]]; then
			startup_cmd=$startup_cmd" --spring.database.type=mysql"
			startup_cmd=$startup_cmd" --spring.datasource.url=$spring_datasource_url"
			startup_cmd=$startup_cmd" --spring.datasource.username=$spring_datasource_username"
			startup_cmd=$startup_cmd" --spring.datasource.password=$spring_datasource_password"
		else
			echoYellow "检测数据库连通性失败"
		fi
	fi
	which java >/dev/null 2>&1
	if [[ 0 != $? ]]; then
		yum install -y java-1.8.0-openjdk
	fi
	pid=$(app_PID)
	if [[ "" != "$pid" ]]; then
		echoYellow "nginxwebui 正在运行... PID:$pid"
		exit 1
	fi
	echo "nohup $startup_cmd &> /dev/null &"
	nohup $startup_cmd &>/dev/null &
}
function app_stop() {
	pid=$(app_PID)
	if [[ ""x != "$pid"x ]]; then
		kill -9 $pid
	fi
}
function app_PID() {
	ps aux | grep "java.*-jar $jar_path" | grep -v grep | awk '{print $2}'
}
function app_status() {
	pid=$(app_PID)
	if [[ "" != "$pid" ]]; then
		echoGreen "nginxwebui 正在运行... PID:$pid"
	else
		echoGreen "nginxwebui 未运行"
	fi
}
case "$1" in
start) app_start ;;
stop) app_stop ;;
status) app_status ;;
restart)
	app_stop
	sleep 1
	app_start
	;;
*) echoRed "参数不正确\t例: sh $0 [start|stop|status|restart]" ;;
esac
